package br.org.ifrr.controller;

import java.awt.Image;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletResponse;
import javax.swing.ImageIcon;
import javax.validation.constraints.NotNull;

import org.hibernate.Session;

import br.org.ifrr.model.Empenho;
import br.org.ifrr.repository.Empenhos;
import br.org.ifrr.util.jsf.FacesUtil;
import br.org.ifrr.util.report.ExecutorRelatorio;

@Named
@RequestScoped
public class RelatorioEmpenhoBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private Empenho empenho;

	@Inject
	private FacesContext facesContext;

	@Inject
	private HttpServletResponse response;

	@Inject
	private EntityManager manager;

	@Inject
	private Empenhos empenhos;

	public void emitirEmpenho() {

		Map<String, Object> parametros = new HashMap<>();

		Image logo = new ImageIcon(getClass().getResource(
				"/resources/images/brasao.jpg")).getImage();
		parametros.put("logo", logo);

		parametros.put("empenho", this.empenho.getEmpenhoNumero());

		ExecutorRelatorio executor = new ExecutorRelatorio(
				"/relatorios/relatorio_empenho.jasper", this.response,
				parametros,
						this.empenho.getEmpenhoNumero() + " - "
						+ new SimpleDateFormat("dd/MM/yyyy").format(new Date())
						+ ".pdf");

		Session session = manager.unwrap(Session.class);
		session.doWork(executor);
		
		if (executor.isRelatorioGerado()) {
			facesContext.responseComplete();
		} else {

			FacesUtil.addErrorMessage("A execução do relatório não retornou dados.");
		}

	}

	@NotNull
	public Empenho getEmpenho() {
		return empenho;
	}

	public void setEmpenho(Empenho empenho) {
		this.empenho = empenho;
	}

	public List<Empenho> completarEmpenho(String empenhoNumero) {
		return this.empenhos.porEmpenho(empenhoNumero);
	}

}